<?php
/*
 * 站点帮助文件
 */

class Site extends Kohana_Url 
{
	private static $_domains = array();

	protected static $_site_type = 'merchant';

    public static function httpDomain ()
    {
		$domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
        return 'http://'.$domain;
    }
    
	/*
	 * 返回当前访问请求的域名
	 *
	 * @return	string	domain
	 */
	public static function domain ($type = NULL)
	{
		if (Kohana::$is_cli)
			return 'localhost';

		switch ($type)
		{
			case 'merchant':
			case 'www'   :
				return self::build_domain('merchant'); break;

			case 'manager':
			case 'admin'   :
				return self::build_domain('admin'); 
				break;

			case 'support':
				return self::build_domain('support'); 
				break;

			case 'api':
				return self::build_domain('api'); 
				break;

			default: 
				return isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
				break;
		}
	}

	public static function subdomain ($index = -4)
	{
		if (Kohana::$is_cli)
			return NULL;

		$domain = self::domain();
		$words  = explode('.', $domain);
		$arr    = array_slice($words, $index, 1);
		if (empty($arr))
			return NULL;
		else
			return $arr[0];
	}

    // 当前是否是通过微信在访问
    // @return boolean
	public static function wechat ()
	{
		$user_agent = empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'];

		// 微信
		if (strpos($user_agent, 'MicroMessenger')) 
			return TRUE;
        else
            return FALSE;
	}

	/*
	 * 获取或者设置当前分站类型
	 *
	 * @return	string	['manager', 'merchant']
	 */
	public static function type ($key = NULL)
	{
		if (empty($key))
		{
			if (empty(self::$_site_type))
				self::$_site_type = 'merchant';
			return self::$_site_type;
		}
		else
		{
			self::$_site_type = $key;
			return self::$_site_type;
		}
	}

	/*
	 * 构建分站域名
	 */
	private static function build_domain ($sub) 
	{
		if (isset(self::$_domains[$sub]))
			return self::$_domains[$sub];

		$domain = self::domain();
		$words  = explode('.', $domain);

		$domain = join('.', array_slice($words, -3, 3));
		if ($sub != 'merchant')
			$domain = "{$sub}.{$domain}";

		self::$_domains[$sub] = $domain;
		return self::$_domains[$sub];
	}
}
